import Xml,os,scheduler,InterfaceExt
 
def __checkBackupDir(path):
    if os.access(path,os.F_OK) and os.access(path,os.W_OK):
        return True
    else:
        return False   
    
def __checkFiles(li):
    """Will check that each compulsory file is existing otherwise will create the missing ones"""
    
    for element in li:
        if not os.access(element, os.F_OK):
            print 'Important System files are missing. The software will try to recreate them, if it happen again please re-install the software'
            createDirs()
            createFiles()
    
def __checkSchedTasks():
    """Will check that all the compulsory schedule tasks exist or will create them"""
    
    list=scheduler.getListOfSchedTasks()
    if 'EBT-Startup.job' or 'EBT-Loggon.job' or 'EBT-Monthly.job' not in list:
        createTasks()

def Check_and_retrieve():
    """Call each of the checking functions"""
    
    __checkSchedTasks()
    __checkFiles(__retrieveInfo())
    __checkAddedToBackupList()
    #__checkPastSchedTasks()
    
def __retrieveInfo():
    """Return a dictionnary with all the necessary paths"""
    
    if os.access('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', os.F_OK):
        li = Xml.retrieveAllXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml')
        return li
    else:
        createDir('C:\\Documents and Settings\\All Users\\Application Data\\EBT')
        createSetupFile()
        
def __checkAddedToBackupList():
    """Check that each of the backupfiles are existing in the backup directory otherwise create them"""
    
    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    if __checkBackupDir(list[0])==True:
        listAllBackup = Xml.retrieveAllXml('C:\\Program Files\\EasyBackupTool\\backupFile.xml')
        listBackup=os.listdir(list[0])
        myresult=[]
        for element in listAllBackup:
            if os.path.basename(element) not in listBackup:
                myresult.append(element)
        #print myresult
        InterfaceExt.initialisationBackup(myresult)
    else:
        print 'Error: BackupDirectory does not exist or do not have sufficient permissions to access it'

def createDir(path,nameDir):
    """Generic method to create a directory"""
    
    if not os.path.isdir(path + nameDir + "\\"):
        os.mkdir(path + nameDir + "\\")
        
def createSetupFile():
    """Create the setup file that holds the important paths for a correct behaviour of the software"""
    
    list= ['C:\\Program Files\\Xdelta\\xdelta30t.exe','C:\\Program Files\\setacl\\SetACL.exe', 'C:\\BackupDir', 'C:\\Program Files\\EasyBackupTool']
    Xml.createXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml','URLs',list)
    
def createBackupTimesFile():
    """Create an xml file that hold the time and date of when the last backup occured for each file"""
    
    listTimeBackups =['0']
    Xml.createXml('C:\\Program Files\\EasyBackupTool\\BackupTimes.xml', 'TimeOfLastBackup', listTimeBackups)

def createBackupListFile(path='C:\\Documents and Settings\\Feez\\Desktop\\test', list=[]):
    """Create an xml file holding the path of each file to backup using either a directory path or a list containing paths"""
    
    if len(list)==0:
        listBackup=os.listdir(path)
        listBackupFP=[]
        for x in listBackup:
            listBackupFP.append("".join(path+x))
        Xml.addToXml('C:\\Program Files\\EasyBackupTool\\backupFile.xml', listBackupFP)
    else:
        Xml.addToXml('C:\\Program Files\\EasyBackupTool\\backupFile.xml', list)
    #__checkAddedToBackupList()

def Install():
    """General Methods that create all the necessary directories, files and tasks for a correct behaviour of the software"""
    
    createDirs()
    createFiles()
    createTasks()
    
def createFiles():
    """Methods that creates the neccessary files for the software"""
    
    createSetupFile()
    createBackupTimesFile()
    createBackupListFile()
    checkFiles()
    
def createDirs():
    """Methods that creates the neccessary directories for the software"""
    
    createDir('C:\\Documents and Settings\\All Users\\Application Data\\', 'EBT')
    createDir('C:\\', 'BackupDir')
    createDir('C:\\Program Files\\', 'EasyBackupTool')

def createTasks():
    """Methods that creates the neccessary tasks for the software"""
    
    #System Startup task
    command = '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\EBT.py"'
    scheduler.create_task('EBT-Startup', command, 'SystemStart')
    
    #Loggon task
    command1 = '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\DynamicScheduling.py"'
    scheduler.create_task('EBT-Loggon', command1, 'Loggon')
    
    #Monthly task
    command2 = '"c:\\python25\\python.exe" "C:\\Documents and Settings\\Feez\\workspace\\Core-IncrementalBackup\\src\\CoreHandling\\MonthlyCleanup.py"'
    scheduler.create_task('EBT-Monthly', command2, 'Monthly')
    